class Node(object):
    # 初始化
    def __init__(self,data=None):
        self.data = data
        self.next = None

class List(object):
    def __init__(self):
        self.head = Node()
        self.length = 0

    def insert(self, pos, data):
        # 判断条件，如果条件不成立返回一个错误msg
        assert pos >= 0 and pos <= self.length
        # 指针从head开始
        tmpPtr = self.head
        # 找到要插入的位置
        while pos > 0:
            tmpPtr = tmpPtr.next
            pos -= 1

        newNode = Node()
        newNode.data = data
        newNode.next = tmpPtr.next
        tmpPtr.next = newNode
        self.length += 1

    def update(self, pos, data):
        # self.remove(pos)
        # self.insert(pos, data)
        tmpPtr = self.head
        while pos > 0:
            tmpPtr = tmpPtr.next
            pos -= 1

        tmpPtr.data = data

    def append(self, data):
        self.insert(self.length, data)

    def remove(self, pos):
        assert pos < self.length

        tmpPtr =self.head
        while pos >0:
            tmpPtr = tmpPtr.next
            pos -= 1

        if tmpPtr.next is not None:
            delNode = tmpPtr.next
            tmpPtr.next = delNode.next
            self.length -= 1
    # 遍历
    def foreach(self):
        tmpPtr = self.head.next
        while tmpPtr is not None:
            # 返回指针指向的值
            yield tmpPtr.data
            tmpPtr = tmpPtr.next


if __name__ == '__main__':

    l = List()
    l.append(1)
    l.append(2)
    l.append(3)
    l.insert(2, 5)
    l.insert(4, 8)
    # l.remove(3)
    l.update(1, 9)
    for i in l.foreach():
        print(i)
